// 通知服务管理
import { apiRequest } from './api'
export interface NotificationOptions {
  title: string
  body: string
  icon?: string
  badge?: string
  tag?: string
  requireInteraction?: boolean
  actions?: Array<{
    action: string
    title: string
    icon?: string
  }>
  data?: any
}

export class NotificationService {
  private static instance: NotificationService
  private permission: NotificationPermission = 'default'
  private settings = {
    enabled: true,
    sound: true,
    requireInteraction: false
  }

  constructor() {
    this.init()
  }

  static getInstance(): NotificationService {
    if (!NotificationService.instance) {
      NotificationService.instance = new NotificationService()
    }
    return NotificationService.instance
  }

  private async init() {
    // 检查浏览器支持
    if (!('Notification' in window)) {
      console.warn('此浏览器不支持通知功能')
      return
    }

    // 获取当前权限状态
    this.permission = Notification.permission

    // 从localStorage加载设置
    this.loadSettings()

    // 注册Service Worker（如果支持）
    if ('serviceWorker' in navigator) {
      try {
        const registration = await navigator.serviceWorker.register('/sw.js')
        console.log('Service Worker 注册成功:', registration)
      } catch (error) {
        console.log('Service Worker 注册失败:', error)
      }
    }
  }

  private loadSettings() {
    try {
      const savedSettings = localStorage.getItem('aide_settings')
      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        this.settings = {
          enabled: settings.notifications ?? true,
          sound: settings.notificationSound ?? true,
          requireInteraction: settings.requireInteraction ?? false
        }
      }
    } catch (error) {
      console.error('加载通知设置失败:', error)
    }
  }

  // 请求通知权限
  async requestPermission(): Promise<NotificationPermission> {
    if (!('Notification' in window)) {
      return 'denied'
    }

    if (this.permission === 'granted') {
      return 'granted'
    }

    try {
      this.permission = await Notification.requestPermission()
      return this.permission
    } catch (error) {
      console.error('请求通知权限失败:', error)
      return 'denied'
    }
  }

  // 检查是否可以发送通知
  canSendNotification(): boolean {
    return (
      'Notification' in window &&
      this.permission === 'granted' &&
      this.settings.enabled
    )
  }

  // 发送通知
  async sendNotification(options: NotificationOptions): Promise<Notification | null> {
    if (!this.canSendNotification()) {
      console.warn('无法发送通知：权限不足或通知已禁用')
      return null
    }

    try {
      const notification = new Notification(options.title, {
        body: options.body,
        icon: options.icon || '/icon-192x192.png',
        badge: options.badge || '/icon-192x192.png',
        tag: options.tag,
        requireInteraction: options.requireInteraction || this.settings.requireInteraction,
        data: options.data,
        silent: !this.settings.sound
      })

      // 设置点击事件
      notification.onclick = (event) => {
        event.preventDefault()
        window.focus()
        
        // 处理通知数据
        if (options.data?.taskId) {
          window.location.href = `#/task/${options.data.taskId}`
        } else if (options.data?.action) {
          this.handleNotificationAction(options.data.action, options.data)
        }
        
        notification.close()
      }

      // 自动关闭通知（如果不需要交互）
      if (!options.requireInteraction) {
        setTimeout(() => {
          notification.close()
        }, 5000)
      }

      return notification
    } catch (error) {
      console.error('发送通知失败:', error)
      return null
    }
  }

  // 处理通知操作
  private handleNotificationAction(action: string, data: any) {
    switch (action) {
      case 'complete_task':
        // 标记任务完成
        this.completeTask(data.taskId)
        break
      case 'snooze':
        // 延迟提醒
        this.snoozeReminder(data.taskId, data.minutes || 15)
        break
      case 'view_task':
        // 查看任务详情
        window.location.href = `#/task/${data.taskId}`
        break
      default:
        console.log('未知的通知操作:', action)
    }
  }

  // 发送任务提醒
  async sendTaskReminder(task: {
    id: string
    title: string
    dueDate?: string
    priority: string
  }) {
    const now = new Date()
    const dueDate = task.dueDate ? new Date(task.dueDate) : null
    
    let body = `任务：${task.title}`
    let tag = `task-${task.id}`
    
    if (dueDate) {
      const timeDiff = dueDate.getTime() - now.getTime()
      const hoursUntilDue = Math.round(timeDiff / (1000 * 60 * 60))
      
      if (hoursUntilDue < 0) {
        body = `⚠️ 已逾期 ${Math.abs(hoursUntilDue)} 小时`
        tag = `overdue-${task.id}`
      } else if (hoursUntilDue === 0) {
        body = `⏰ 即将到期`
      } else if (hoursUntilDue <= 24) {
        body = `⏰ ${hoursUntilDue} 小时后到期`
      }
    }

    const priorityEmoji = {
      'P0': '🔴',
      'P1': '🟡', 
      'P2': '🟢',
      'P3': '🔵'
    }[task.priority] || '📋'

    return this.sendNotification({
      title: `${priorityEmoji} AIDE 任务提醒`,
      body,
      tag,
      requireInteraction: task.priority === 'P0', // 高优先级任务需要用户交互
      actions: [
        {
          action: 'complete_task',
          title: '标记完成'
        },
        {
          action: 'snooze',
          title: '延迟15分钟'
        },
        {
          action: 'view_task',
          title: '查看详情'
        }
      ],
      data: {
        taskId: task.id,
        type: 'task_reminder'
      }
    })
  }

  // 发送每日总结通知
  async sendDailySummary(stats: {
    completedTasks: number
    pendingTasks: number
    overdueTasks: number
  }) {
    const { completedTasks, pendingTasks, overdueTasks } = stats
    
    let body = `今日完成 ${completedTasks} 个任务`
    if (pendingTasks > 0) {
      body += `，还有 ${pendingTasks} 个待完成`
    }
    if (overdueTasks > 0) {
      body += `，${overdueTasks} 个已逾期`
    }

    return this.sendNotification({
      title: '📊 AIDE 每日总结',
      body,
      tag: 'daily-summary',
      data: {
        type: 'daily_summary',
        action: 'view_stats'
      }
    })
  }

  // 发送重复任务生成通知
  async sendRecurringTaskNotification(taskTitle: string, nextDueDate: string) {
    return this.sendNotification({
      title: '🔄 重复任务已生成',
      body: `${taskTitle} - 下次执行时间：${nextDueDate}`,
      tag: 'recurring-task',
      data: {
        type: 'recurring_task'
      }
    })
  }

  // 完成任务（通过通知操作）
  private async completeTask(taskId: string) {
    try {
      // 调用API切换任务状态（使用统一的toggle接口）
      await apiRequest(`/tasks/${taskId}/toggle`, {
        method: 'PATCH'
      })
      
      this.sendNotification({
        title: '✅ 任务已完成',
        body: '任务已标记为完成',
        tag: `completed-${taskId}`
      })
    } catch (error) {
      console.error('完成任务失败:', error)
    }
  }

  // 延迟提醒
  private snoozeReminder(taskId: string, minutes: number) {
    setTimeout(() => {
      // 重新发送提醒（这里需要重新获取任务数据）
      console.log(`${minutes}分钟后重新提醒任务: ${taskId}`)
    }, minutes * 60 * 1000)

    this.sendNotification({
      title: '⏰ 提醒已延迟',
      body: `将在 ${minutes} 分钟后再次提醒`,
      tag: `snoozed-${taskId}`
    })
  }

  // 更新设置
  updateSettings(newSettings: Partial<typeof this.settings>) {
    this.settings = { ...this.settings, ...newSettings }
    
    // 保存到localStorage
    try {
      const savedSettings = localStorage.getItem('aide_settings')
      const allSettings = savedSettings ? JSON.parse(savedSettings) : {}
      allSettings.notifications = this.settings.enabled
      allSettings.notificationSound = this.settings.sound
      allSettings.requireInteraction = this.settings.requireInteraction
      localStorage.setItem('aide_settings', JSON.stringify(allSettings))
    } catch (error) {
      console.error('保存通知设置失败:', error)
    }
  }

  // 获取权限状态
  getPermissionStatus(): NotificationPermission {
    return this.permission
  }

  // 获取设置
  getSettings() {
    return { ...this.settings }
  }

  // 清除所有通知
  clearAllNotifications() {
    if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
      navigator.serviceWorker.controller.postMessage({
        type: 'CLEAR_NOTIFICATIONS'
      })
    }
  }
}

// 导出单例实例
export const notificationService = NotificationService.getInstance()
